﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using Caliburn.Micro;
using Wulong.Phone.Dianping.Constants;
using Wulong.Phone.Dianping.Helpers;
using Wulong.Phone.Dianping.Models;
using Wulong.Phone.Dianping.Services;

namespace Wulong.Phone.Dianping.ViewModels
{
    public class GroupOnListViewModel: PaginationViewModelBase
    {
        private readonly IWindowManager _windowManager;
        private IDisposable _disposable;
        public GroupOnListViewModel(
            IWindowManager windowManager)
        {
            _windowManager = windowManager;
            _groupOns = new ObservableCollection<GroupOn>();
        }

        private ObservableCollection<GroupOn> _groupOns;
        public IEnumerable<GroupOn> GroupOns
        {
            get { return _groupOns; }
        }

        private bool _canLoad;
        public bool CanLoad
        {
            get { return _canLoad; }
            set
            {
                _canLoad = value;
                NotifyOfPropertyChange(() => CanLoad);
            }
        }
        public void Load()
        {
            IsBusy = true;
            CanLoad = false;
            Page = 1;
            _groupOns.Clear();
            _disposable = DianpingService.ObservableHotGroupOn(
                DianpingService.GetCity(CityCode).Pinyin, true)
                .ObserveOnDispatcher()
                .Finally(() =>
                {
                    IsBusy = false;
                    CanLoad = true;
                })
                .Subscribe(item => _groupOns.Add(item),
                    error => MessageHelper.ShowErrorMessage());
        }


        public void ViewItem(GroupOn selectedItem)
        {
            if (selectedItem == null) return;
            var vm = new GroupOnItemViewModel(selectedItem.Link);
            _windowManager.ShowDialog(vm);
        }

        protected override void OnDeactivate(bool close)
        {
            base.OnDeactivate(close);
            if (_disposable != null)
                _disposable.Dispose();
        }

        protected override void OnViewReady(object view)
        {
            base.OnViewReady(view);
            if (_groupOns.Count == 0)
                Load();
        }
    }
}
